package com.aurora.source.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.source.SourceApplication;
import com.aurora.source.util.SPUtils;
import com.aurora.source.util.ScreenUtils;
import com.aurora.source.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;

import java.util.Map;

import butterknife.ButterKnife;

/**
 * Base Activity
 * <p>
 * Created by Lance
 * 2018/07/05.
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity
        implements IBaseView {

    protected T basePresenter;

    protected View mContentView;
    public BaseActivity activity;
    public SourceApplication application;

    public Map<String, String> params;// 请求数据Map

    public String userId;
    private ProgressDialog mProgressDialog;
    String mDataLoading;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            basePresenter = attach();
            activity = this;
            application = (SourceApplication) getApplication();
            userId = (String) SPUtils.get(this,SPUtils.USER_ID,"");
            setBaseView(bindLayout());
            ButterKnife.bind(this);
            Bundle bundle = getIntent().getExtras();
            initData(bundle);
            ScreenUtils.setCustomdensity(activity, application);
            initView(savedInstanceState, mContentView);
            doBusiness();
            application.addActivity(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("ResourceType")
    protected void setBaseView(@LayoutRes int layoutId) {
        try {
            if (layoutId <= 0) return;
            setContentView(mContentView = LayoutInflater.from(this).inflate(layoutId, null));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public abstract class OnMultiClickListener implements View.OnClickListener {
        // 两次点击按钮之间的点击间隔不能少于1000毫秒
        private static final int MIN_CLICK_DELAY_TIME = 1000;
        private long lastClickTime;

        public abstract void onMultiClick(View v);

        @Override
        public void onClick(View v) {
            long curClickTime = System.currentTimeMillis();
            if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                // 超过点击间隔后再将lastClickTime重置为当前点击时间
                lastClickTime = curClickTime;
                onMultiClick(v);
            }
        }
    }

    /**
     * Activity 跳转
     * finish 是否删除当前Activity
     *
     * @author Lance
     * created at 2017/6/9
     */
    public void gotoActivity(Class<? extends Activity> clazz, boolean finish) {
        try {
            Intent intent = new Intent(this, clazz);
            this.startActivity(intent);
            if (finish) {
                hideSoftInput();
                this.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void gotoActivityForResult(Class<? extends Activity> clazz, int requstCode) {
        try {
            Intent intent = new Intent(this, clazz);
            this.startActivityForResult(intent,requstCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void gotoActivityForResult(Class<? extends Activity> clazz, int requstCode,Bundle bundle) {
        try {
            Intent intent = new Intent(this, clazz);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            this.startActivityForResult(intent,requstCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public abstract T attach();
    /**
     * Activity 跳转
     * finish 是否删除当前Activity
     *
     * @author Lance
     * created at 2018/02/24
     */
    public void gotoActivity(Class<? extends Activity> clazz, boolean finish, Bundle bundle) {
        try {
            Intent intent = new Intent(this, clazz);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            this.startActivity(intent);
            if (finish) {
                hideSoftInput();
                this.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 吐司 资源文件 文本
    public void showToast(int resId) {
        try {
            ToastUtils.showSingletonShort(activity, resId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    // 吐司 内容
    public void showToast(String stringRes) {
        try {
            ToastUtils.showSingletonShort(activity, stringRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取版本号
    public String getVersion() {
        int verCode = 0;
        try {
            verCode = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(verCode);
    }

    // 隐藏软键盘
    public void hideKeyBoard() {
        try {
            InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen = inputMgr.isActive();
            if (!isOpen) {
                inputMgr.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);// 输入法软键盘打开时关闭,关闭时打开
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hideSoftInput() {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 打开软键盘
    public void openKeyBoard() {
        try {
            InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen = inputMgr.isActive();
            if (isOpen) {
                inputMgr.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);// 输入法软键盘打开时关闭,关闭时打开
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取 文本
    @NonNull
    public String getText(TextView view) {
        try {
            return view.getText().toString().trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (basePresenter != null) {
            basePresenter.detachView();
        }
        hideSoftInput();
    }

    // 判断字符串是否为空或空字符串
    public boolean isEmpty(String str) {
        return TextUtils.isEmpty(str);
    }

    // 打开相册/拍照
    public void showPictureSelector(int MaxSelect,boolean isCrop) {
        try {
            PictureSelector.create(activity)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(MaxSelect)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .setOutputCameraPath(application.getFilesDir().getAbsolutePath())// 自定义拍照保存路径,可不填
                    .enableCrop(isCrop)// 是否裁剪 true or false
                    .withAspectRatio(1,1)// 裁剪是否可旋转图片 true or false
                    .rotateEnabled(true)// 裁剪是否可旋转图片 true or false
                    .isDragFrame(false)// 是否可拖动裁剪框(固定)
                    .previewImage(true)//是否可预览图片 true or false
                    .previewVideo(true)//是否可预览视频 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .compressSavePath(application.getFilesDir().getAbsolutePath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                    .openClickSound(true)// 是否开启点击声音 true or false
                    .cropCompressQuality(80)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 打开相册/拍照
    public void showVideoSelector(int MaxSelect) {
        try {
            PictureSelector.create(activity)
                    .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(MaxSelect)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .setOutputCameraPath(application.getFilesDir().getAbsolutePath())// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .compressSavePath(application.getFilesDir().getAbsolutePath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                    .openClickSound(true)// 是否开启点击声音 true or false
                    .cropCompressQuality(80)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(10000)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    .forResult(PictureConfig.REQUEST_CAMERA);//结果回调onActivityResult code
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void initProgressDialog(String mMessage,boolean isCancelable,DialogInterface.OnCancelListener mProgressCancelListener) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(activity);
            if (TextUtils.isEmpty(mMessage)) {
                mDataLoading = activity.getString(R.string.data_loading);
                mProgressDialog.setMessage(mDataLoading);
            } else {
                mProgressDialog.setMessage(mMessage);
            }
            mProgressDialog.setCancelable(isCancelable);

            if (isCancelable) {
                mProgressDialog.setOnCancelListener(mProgressCancelListener);
            }

            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }
        }
    }

    protected void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
}